﻿using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;

namespace FriendFunny.Tool.DependencyInjection
{
    /// <summary>
    /// 生命周期注册扩展方法
    /// </summary>
    public static class DependencyInjectionExtensions
    {
        /// <summary>
        /// 注册依赖服务生命周期
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection RegisterService(this IServiceCollection services)
        {
            var stopwatch = new Stopwatch();
            var lifetimeInterfaces = new[] { typeof(ITransient), typeof(IScoped), typeof(ISingleton) };

            foreach (var lifetime in lifetimeInterfaces) 
            {
                List<Type> types = AppDomain.CurrentDomain.GetAssemblies()
                                                          .SelectMany(x => x.GetTypes())
                                                          .Where(x => lifetime.IsAssignableFrom(x) && x.IsClass && !x.IsAbstract)
                                                          .ToList();
                foreach (var type in types) 
                {
                    Type[] interfaces = type.GetInterfaces();
                    foreach (var item in interfaces)
                    {
                        if (lifetime == typeof(ITransient))
                            services.AddTransient(item, type);
                        else if (lifetime == typeof(IScoped))
                            services.AddScoped(item, type);
                        else if (lifetime == typeof(ISingleton))
                            services.AddSingleton(item, type);
                    }
                }
            }

            return services;
        }
    }
}
